//
//  TimeSecondPickView.m
//  wtshoppingcite
//
//  Created by Baojia-LC on 14/11/12.
//  Copyright (c) 2014年 TW. All rights reserved.
//

#import "TimeSecondPickView.h"
#import "NSDate+category.h"
@implementation TimeSecondPickView

-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        self.backgroundColor = [UIColor whiteColor];
        _selectIndexpath = [NSIndexPath indexPathForRow:0 inSection:0];
        _timeSelectIndexpath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self startLoadData];
        [self createSubView];
    }
    return self;
}

-(void)startLoadData{
    NSDate* date = [NSDate date];
    //获取一个月的天数
    int days = [[NSString getCurrentDays:date] intValue];
    int curday = [[NSString getCurrentDay:date] intValue];
    
    //获取下个月的日期
    NSDate* nextDate = [NSDate getPriousorLaterDateFromDate:date withMonth:1];
    int nextday = [[NSString getCurrentDay:nextDate] intValue];
    
    NSMutableArray* daysArray = [[NSMutableArray alloc] initWithCapacity:0];
    int j = 0;
    for(int i = curday;i<=days+nextday;i++){
        NSMutableDictionary* dic = [[NSMutableDictionary alloc] initWithCapacity:0];
        NSDate* idate = [NSDate getPriousorLaterDateFromDate:date withDay:j];
        int iday = [[NSString getCurrentDay:idate] intValue];
        int month = [[NSString getCurrentMonth:idate] intValue];
        int year = [[NSString getCurrentYear:idate] intValue];
        int weekday = [[NSString getCurrentWeek:idate] intValue]-1;
        NSString* hweek = [NSString getCurrentHaziWeek:weekday];
        
        NSString* y = [NSString stringWithFormat:@"%d",year];
        NSString* cd = [NSString stringWithFormat:@"%02d-%02d",month,iday];
        NSString* wd = [NSString stringWithFormat:@"星期%@",hweek];
        [dic setObject:y forKey:@"year"];
        [dic setObject:cd forKey:@"date"];
        [dic setObject:wd forKey:@"week"];
        [daysArray addObject:dic];
        
        j++;
    }
    
    _dayData = daysArray;
    
    NSMutableArray* timeArray = [[NSMutableArray alloc] initWithCapacity:0];
    for(int i = 0;i<24;i++){
        NSString* gay;
        if(i == 23){
            gay = [NSString stringWithFormat:@"%02d-00 00-00",i];
        }else{
            gay = [NSString stringWithFormat:@"%02d-00 %02d-00",i,i+1];
        }
        [timeArray addObject:gay];
    }
    _timeData = timeArray;
    
}

-(void)createSubView{
    
    self.titleLabel = [self createLabelWithFrame:CGRectMake(0, 5, SCREEN_WIDTH, 20) text:@"" font:16 textAli:NSTextAlignmentCenter textColor:MAIN_GRAY_COLOR];
    [self addSubview:self.titleLabel];
    
    self.dayTableView = [[UITableView alloc] initWithFrame:CGRectMake(10, self.titleLabel.bottom+10, (SCREEN_WIDTH-30)/2, 100) style:UITableViewStylePlain];
    self.dayTableView.backgroundColor = COLOR_RGB(239, 239, 239);
    self.dayTableView.layer.cornerRadius = 5;
    self.dayTableView.clipsToBounds = YES;
    self.dayTableView.layer.borderColor = COLOR_RGB(206, 206, 206).CGColor;
    self.dayTableView.layer.borderWidth = 1;
    self.dayTableView.delegate = self;
    self.dayTableView.dataSource = self;
    [self addSubview:self.dayTableView];
    
    self.timeTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.dayTableView.right + 10, self.dayTableView.top , (SCREEN_WIDTH-30)/2, 100) style:UITableViewStylePlain];
    self.timeTableView.backgroundColor = COLOR_RGB(239, 239, 239);
    self.timeTableView.layer.cornerRadius = 5;
    self.timeTableView.layer.borderColor = COLOR_RGB(206, 206, 206).CGColor;
    self.timeTableView.layer.borderWidth = 1;
    self.timeTableView.clipsToBounds = YES;
    self.timeTableView.delegate = self;
    self.timeTableView.dataSource = self;
    [self addSubview:self.timeTableView];
    
    UIButton* cancleButton = [[UIButton alloc] initWithFrame:CGRectMake(0, self.dayTableView.bottom + 10, SCREEN_WIDTH/2-1, 40)];
    [cancleButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancleButton setTitleColor:MAIN_GRAY_COLOR forState:UIControlStateNormal];
    [cancleButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [cancleButton setBackgroundColor:COLOR_RGB(238, 238, 238)];
    cancleButton.tag = 1000;
    UIImage* ima = [UIImage createImageWithBgColor:MAIN_BLUE_COLOR size:CGSizeMake(SCREEN_WIDTH/2, 40) cornerRadius:0];
    [cancleButton setBackgroundImage:ima forState:UIControlStateHighlighted];
    [cancleButton addTarget:self action:@selector(chooseClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:cancleButton];
    
    UIButton* sureButton = [[UIButton alloc] initWithFrame:CGRectMake(cancleButton.right+1, self.dayTableView.bottom + 10, SCREEN_WIDTH/2-1, 40)];
    [sureButton setTitle:@"确定" forState:UIControlStateNormal];
    [sureButton setTitleColor:MAIN_GRAY_COLOR forState:UIControlStateNormal];
    [sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [sureButton setBackgroundColor:COLOR_RGB(238, 238, 238)];
    sureButton.tag = 1001;
    [sureButton setBackgroundImage:ima forState:UIControlStateHighlighted];
    [sureButton addTarget:self action:@selector(chooseClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:sureButton];
    
    self.height = self.dayTableView.height+self.titleLabel.height+sureButton.height+20;
}

-(void)chooseClick:(UIButton*)button{
    [self dismissView];
    int index = button.tag - 1000;
    if(index == 1){
        NSDictionary* daydic = [_dayData objectAtIndex:_selectIndexpath.row];
        NSString* time = [_timeData objectAtIndex:_timeSelectIndexpath.row];
        NSString* year = [daydic objectForKey:@"year"];
        NSString* monthday = [daydic objectForKey:@"date"];
        NSString* date = [NSString stringWithFormat:@"%@-%@ %@",year,monthday,time];
        if(_selectBlock != nil){
            _selectBlock(index,date);
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(_dayTableView == tableView){
        return _dayData.count;
    }else{
        return _timeData.count;
    }
    return 0;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(_dayTableView == tableView){
        
        static NSString* indentify = @"daycell";
        UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:indentify];
        if(cell == nil){
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentify];
            UILabel* dlabel = [self createLabelWithFrame:CGRectMake(15, 7, 60, 20) text:@"" font:15 textAli:NSTextAlignmentLeft textColor:MAIN_GRAY_COLOR];
            dlabel.tag = 100;
            [cell.contentView addSubview:dlabel];
            
            UILabel* wlabel = [self createLabelWithFrame:CGRectMake(dlabel.right, dlabel.top, 80, 20) text:@"" font:15 textAli:NSTextAlignmentLeft textColor:MAIN_GRAY_COLOR];
            wlabel.tag = 101;
            [cell.contentView addSubview:wlabel];
        }
        UILabel* dlabel = (UILabel*)[cell.contentView viewWithTag:100];
        UILabel* wlabel = (UILabel*)[cell.contentView viewWithTag:101];
        dlabel.text = [[_dayData objectAtIndex:indexPath.row] objectForKey:@"date"];
        wlabel.text = [[_dayData objectAtIndex:indexPath.row] objectForKey:@"week"];
        
        if(_selectIndexpath.row == indexPath.row){
            dlabel.textColor = MAIN_BLUE_COLOR;
            wlabel.textColor = MAIN_BLUE_COLOR;
            cell.backgroundColor = [UIColor whiteColor];
        }
        else{
            dlabel.textColor = MAIN_GRAY_COLOR;
            wlabel.textColor = MAIN_GRAY_COLOR;
            cell.backgroundColor = [UIColor clearColor];
            
        }
        
        //        cell.backgroundColor = [UIColor clearColor];
        //        UIView* imgV = [[UIImageView alloc] initWithFrame:cell.frame];
        //        cell.selectedBackgroundView = imgV;
        //        cell.selectedBackgroundView.backgroundColor = [UIColor whiteColor];
        
        return cell;
        
    }else{
        static NSString* indentify = @"timecell";
        UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:indentify];
        if(cell == nil){
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentify];
            UILabel* gaylabel = [self createLabelWithFrame:CGRectMake(15, 7, 120, 20) text:@"" font:15 textAli:NSTextAlignmentLeft textColor:MAIN_GRAY_COLOR];
            gaylabel.tag = 103;
            [cell.contentView addSubview:gaylabel];
        }
        UILabel* gaylabel = (UILabel*)[cell.contentView viewWithTag:103];
        gaylabel.text = [_timeData objectAtIndex:indexPath.row];
        
        cell.backgroundColor = [UIColor clearColor];
        UIView* imgV = [[UIImageView alloc] initWithFrame:cell.frame];
        cell.selectedBackgroundView = imgV;
        cell.selectedBackgroundView.backgroundColor = [UIColor whiteColor];
        
        if(_timeSelectIndexpath.row == indexPath.row){
            gaylabel.textColor = MAIN_BLUE_COLOR;
            cell.backgroundColor = [UIColor whiteColor];
        }else{
            gaylabel.textColor = MAIN_GRAY_COLOR;
            cell.backgroundColor = [UIColor clearColor];
        }
        return cell;
        
    }
    return nil;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 34;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView == _dayTableView){
        //        _daySelectArray = @[_selectIndexpath,indexPath];
        //        [tableView reloadRowsAtIndexPaths:_daySelectArray withRowAnimation:UITableViewRowAnimationFade];
        _selectIndexpath = indexPath;
        [tableView reloadData];
    }else{
        _timeSelectIndexpath = indexPath;
        [tableView reloadData];
    }
}

-(void)showView:(UIView*)superView{
    
    _backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _backView.backgroundColor = Color(200, 200, 200, 0.4);
    [superView addSubview:_backView];
    
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapView:)];
    [_backView addGestureRecognizer:tap];
    
    [superView bringSubviewToFront:self];
    
    //    dispatch_async(dispatch_get_main_queue(), ^{
    //        [UIView animateWithDuration:0.4 animations:^{
    //            self.alpha = 1.0f;
    //            self.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0,(SCREEN_HEIGHT - self.height)/2);
    //        }];
    //    });
    
    [UIView animateWithDuration:0.5
                          delay:0.0
         usingSpringWithDamping:0.6
          initialSpringVelocity:4.0
                        options:UIViewAnimationOptionBeginFromCurrentState|UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         self.top = (superView.height - self.height)/2;
                         self.alpha = 1.0;
                     } completion:^(BOOL finished) {
                         
                     }];
}

-(void)tapView:(UITapGestureRecognizer*)tap{
    [self dismissView];
}

-(void)dismissView{
    
    [_backView removeFromSuperview];
    _backView = nil;
    
    //    [UIView animateWithDuration:0.4 animations:^{
    //        self.alpha = 0.0f;
    //        self.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, 0);
    //    }];
    [UIView animateWithDuration:0.2 animations:^{
        self.top = self.top + 20;
    } completion:^(BOOL finished){
        if(finished){
            [UIView animateWithDuration:0.3
                                  delay:0.0
                                options:UIViewAnimationOptionBeginFromCurrentState|UIViewAnimationOptionCurveEaseInOut
                             animations:^ {
                                 self.top = -self.height;
                                 self.alpha = 0;
                             } completion:^(BOOL finished) {
                                 [self removeFromSuperview];
                             }];
        }
    }];
    
}

-(UILabel*)createLabelWithFrame:(CGRect)frame text:(NSString*)text font:(int)font textAli:(NSTextAlignment)alig textColor:(UIColor*)tc{
    
    if(text == nil)
        text = @"";
    UILabel* label = [[UILabel alloc] initWithFrame:frame];
    label.text = text;
    label.font = [UIFont systemFontOfSize:font];
    label.textAlignment = alig;
    label.textColor = tc;
    label.backgroundColor = [UIColor clearColor];
    return label;
    
}

@end
